package com.xnyzc.lhy.order.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.component.config.security.RocketConfig;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MqConstant;
import com.xnyzc.lhy.common.constant.MqConsumerGroupConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.order.entity.gps.DriverAppointmentLocation;
import com.xnyzc.lhy.order.entity.mq.OaCOrderPersonal;
import com.xnyzc.lhy.order.entity.param.synchronization.LocationSyncParam;
import com.xnyzc.lhy.order.feign.didi.IDidiService;
import com.xnyzc.lhy.order.service.gps.IDriverAppointmentLocationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 司机位置同步消费
 * @author c
 */
@Slf4j
@Component
public class MqDriverPositionSyncConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    RocketConfig config;

    @Autowired
    RedisCommon redisCommon;

    @Value("${rocketMq.isStart}")
    private boolean isStart;

    @Autowired
    private IDidiService iDidiService;

    @Autowired
    private IDriverAppointmentLocationService locationService;

    /**
     * 开启监听
     */
    @PostConstruct
    public void init() {
        try {
            if (!isStart) {
                return;
            }
            consumer = new DefaultMQPushConsumer(MqConsumerGroupConstant.DRIVER_POSITION);
            consumer.setNamesrvAddr(config.getNameServerAddr());
            consumer.subscribe(config.getTopic(), MqConstant.DRIVER_LOCATION_SYNC);
            consumer.setConsumeMessageBatchMaxSize(1);
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                    MessageExt messageExt = msgs.get(0);
                    return MqDriverPositionSyncConsumer.this.dealBody(messageExt);
                }
            });
            consumer.start();
            log.info("---------司机位置同步消费者启动完成-----o(*^▽^*)┛-------");
        } catch (Exception e) {
            log.info("---------司机位置同步消费者初始化失败----(# ﾟДﾟ)--------");
        }
    }

    /**
     * 处理业务逻辑
     *
     * @param messageExt
     * @return
     */
    public ConsumeConcurrentlyStatus dealBody(MessageExt messageExt) {
        LocationSyncParam locationSyncParam = null;
        try {
            //发送的消息
            String body = new String(messageExt.getBody());
            if (CheckUtil.strIsEmpty(body)) {
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
            locationSyncParam = JSON.parseObject(body, LocationSyncParam.class);

            // 推送给滴滴司机位置
            iDidiService.locationSync(locationSyncParam);

            // 判断订单状态，存司机接单 → 到达乘客预约地点
            String str = redisCommon.getStr(RedisPrefixConstant.ORDER_OA_D_ORDER + locationSyncParam.getOrder_id());
            if (CheckUtil.strIsEmpty(str)) {
                log.info("获取订单Redis信息为空，{}", str);
            } else {
                OaCOrderPersonal oaCOrderPersonal = JSONObject.parseObject(str, OaCOrderPersonal.class);
                if (EOrderStatus.reservationLocation.getType().equals(oaCOrderPersonal.getOrderStatus())) {
                    // 添加司机轨迹
                    DriverAppointmentLocation appointmentLocation = new DriverAppointmentLocation();
                    appointmentLocation.setCreateTime(new Date());
                    String driverId;
                    if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getDriverId())) {
                        driverId = oaCOrderPersonal.getDriverId().toString();
                    } else {
                        driverId = locationSyncParam.getDriver_id();
                    }
                    appointmentLocation.setCreateUser(driverId);
                    appointmentLocation.setDriverId(Long.valueOf(driverId));
                    appointmentLocation.setOrderNo(oaCOrderPersonal.getOrderNo());
                    long nextId = IDUtil.nextId();
                    appointmentLocation.setLocationId(nextId);
                    // 都不为空才有存的必要
                    if (CheckUtil.objIsNotEmpty(locationSyncParam.getLng()) && CheckUtil.objIsNotEmpty(locationSyncParam.getLat())) {
                        appointmentLocation.setLng(locationSyncParam.getLng().toString());
                        appointmentLocation.setLat(locationSyncParam.getLat().toString());
                        // 如果数据库中没有才存
                        DriverAppointmentLocation driverAppointmentLocation = locationService.getById(nextId);
                        if (CheckUtil.objIsEmpty(driverAppointmentLocation)) {
                            locationService.save(appointmentLocation);
                        }
                    }
                }
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            log.error("异常信息为：{}", e);
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

}
